import { Body, Controller, Get, Param, Post, Put, Query, Req, UsePipes } from '@nestjs/common';
import { isNumber } from 'class-validator';
import dtoValidationPipe from 'src/pipe/Dto.pipe';
import { errorReturn, successReturn } from 'src/utils';
import { DeviceService } from './device.service';
import ListDto, { AddDto, AllotMerchantDto, EditDto, SetStrategyDto } from './dto';

@Controller('device')
export class DeviceController {
    constructor(
        private deviceService:DeviceService
    ){}

    @Get('list')
    @UsePipes(dtoValidationPipe({skipMissingProperties : true}))
    list(@Query() dto:ListDto, @Req() {roleType, userId}) {
        return this.deviceService.list(dto, roleType, userId)
    }

    @Post('add')
    @UsePipes(dtoValidationPipe())
    async addMerchant(@Body() dto:AddDto) {
       try {
            const rs = await this.deviceService.add(dto)
            console.log(rs)
            return rs ? successReturn('保存成功') : errorReturn('保存失败')
       } catch (error) {
           return errorReturn(error.message)
       }
    }


    @Get('edit/:deviceId')
    async getDeviceEditData(@Param('deviceId') deviceId:number, @Req() { roleType }) {
        deviceId = Number(deviceId)
        if(!isNumber(deviceId) || deviceId <= 0) return errorReturn()
        const data = await this.deviceService.getEditData(deviceId, roleType || 0)
        return successReturn(data)
    }

    @Put('edit/:deviceId')
    @UsePipes(dtoValidationPipe({skipMissingProperties : true, skipNullProperties : true}))
    async edit(@Param('deviceId') deviceId:number, @Body() dto:EditDto, @Req() { roleType }) {
        deviceId = Number(deviceId)
        if(!isNumber(deviceId) || deviceId <= 0) return errorReturn()
        const data = await this.deviceService.edit(deviceId, dto)
        return successReturn(data)
    }


    @Post('allotMerchant')
    @UsePipes(dtoValidationPipe)
    async allotMerchant(@Body() dto:AllotMerchantDto) {
        const res = await this.deviceService.allotMerchant(dto.merchantId, dto.deviceIds)
        return res
    }

    @Post('setStrategy')
    @UsePipes(dtoValidationPipe)
    async setStrategy(@Body() dto:SetStrategyDto) {
        const res = await this.deviceService.setStrategy(dto.strategyId, dto.deviceIds)
        return res
    }
}
